package com.dwx.guli.service.trade.service.impl;

import com.dwx.guli.common.util.HttpClientUtils;
import com.dwx.guli.service.base.exception.GuliException;
import com.dwx.guli.service.base.result.ResultCodeEnum;
import com.dwx.guli.service.trade.entity.Order;
import com.dwx.guli.service.trade.service.OrderService;
import com.dwx.guli.service.trade.service.WeixinPayService;
import com.dwx.guli.service.trade.util.WeixinPayProperties;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class WeixinPayServiceImpl implements WeixinPayService {
    @Autowired
    WeixinPayProperties weixinPayProperties;
    @Autowired
    OrderService orderService;
    @Override
    public Map<String, Object> createNative(String orderNo, String remoteAddr) {
        try {
            Order order = orderService.getOrderByOrderNo(orderNo);
            //appid公众账号ID
            Map<String ,String > params=new HashMap<>();
            params.put("appid",weixinPayProperties.getAppId());
            //mch_id商户号
            params.put("mch_id",weixinPayProperties.getPartner());
            //nonce_str随机字符串
            params.put("nonce_str", WXPayUtil.generateNonceStr());

            params.put("product_id", order.getCourseId());
            //body商品描述
            params.put("body",order.getCourseTitle());
            //out_trade_no商户订单号
            params.put("out_trade_no",orderNo);
            //total_fee标价金额
            params.put("total_fee",order.getTotalFee()+"");
            //spbill_create_ip终端IP
            params.put("spbill_create_ip",remoteAddr);
            //notify_url通知地址
            params.put("notify_url",weixinPayProperties.getNotifyUrl());
            //trade_type交易类型
            params.put("trade_type","NATIVE");
            //sign签名
            String xmlParams = WXPayUtil.generateSignedXml(params, weixinPayProperties.getPartnerKey());
            log.info("\n xmlParams：\n" + xmlParams);

            HttpClientUtils client=new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(xmlParams);
            client.setHttps(true);
            client.post();
            String resultXml = client.getContent();
            log.info("\n resultXml：\n" + resultXml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
            //错误处理
            if("FAIL".equals(resultMap.get("return_code")) || "FAIL".equals(resultMap.get("result_code"))){
                log.error("微信支付统一下单错误 - "
                        + "return_code: " + resultMap.get("return_code")
                        + "return_msg: " + resultMap.get("return_msg")
                        + "result_code: " + resultMap.get("result_code")
                        + "err_code: " + resultMap.get("err_code")
                        + "err_code_des: " + resultMap.get("err_code_des"));

                throw new GuliException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
            }
            Map<String ,Object> map=new HashMap<>();
            map.put("result_code", resultMap.get("result_code"));//响应码
            map.put("code_url", resultMap.get("code_url"));//生成二维码的url
            map.put("course_id", order.getCourseId());//课程id
            map.put("total_fee", order.getTotalFee());//订单总金额
            map.put("out_trade_no", orderNo);//订单号
            return map;
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
        }
    }
}
